package one.stand.controller.index;

import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.PageHelper;
import com.jmp.api.dto.*;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.LiveApi;
import com.jmp.base.dto.LiveListRequest;
import com.jmp.base.dto.*;
import com.jmp.feign.LiveFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.advice.ResultEnum;
import one.stand.dto.Company2Dto;
import one.stand.dto.ConvertUtils;
import one.stand.dto.PageRequest;
import one.stand.dto.PageResponse2;
import one.stand.mapper.GoodsApiCrmAppMapper;
import one.stand.model.Goods;
import one.stand.model.ResultModel;
import one.stand.model.SysDictValue;
import one.stand.service.CompanyBaseService;
import one.stand.service.GoodsBaseService;
import one.stand.service.GoodsPhotoService;
import one.stand.service.sys.SysDictValueService;
import one.stand.util.*;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Api(description = "直播:创建直播|开播||我的直播")
@RestController
@RequestMapping("live")
public class LiveController {
    public static SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm");

    @Autowired
    private LiveFeign liveFeign;

    @Autowired
    private GoodsPhotoService goodsPhotoService;
    @Autowired
    private SysDictValueService sysDictValueService;
    @Autowired
    private GoodsBaseService goodsBaseService;
    @Autowired
    private CompanyBaseService companyBaseService;

    @Autowired
    private GoodsApiCrmAppMapper goodsApiCrmAppMapper;

    @ApiOperation(value = "1直播页(无则创建直播页,有预告进预防页")
    @PostMapping("info")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<LiveInfoApiResponse> info() {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        ResultModel<LiveInfoResponse> infoResponseResultModel = liveFeign.info(LiveInfoRequest.builder().cardId(optUser.getCardId()).build());
        AssertUtil.isTrue(infoResponseResultModel);
        LiveInfoResponse infoResponse = infoResponseResultModel.getData();

        LiveInfoApiResponse response;
        if (infoResponse.isPre()) {//预告
            int goodsNum = 0;
            List<String> goodsPhotos = null;
            ResultModel<LiveGoodsListResponse> goodsListResponseResultModel = liveFeign.goodsList(LiveGoodsListRequest.builder()
                    .cardId(optUser.getCardId())
                    .build());
            AssertUtil.isTrue(goodsListResponseResultModel);
            if (OneListUtil.isNotEmpty(goodsListResponseResultModel.getData().getGoodsIds())) {
                goodsNum = goodsListResponseResultModel.getData().getGoodsIds().size();
                List<LiveGoodsListResponse.Goods> goodsIds = CollUtil.sub(goodsListResponseResultModel.getData().getGoodsIds(), 0, 3);
                goodsPhotos = ConvertUtils.list(goodsIds, goods -> goodsPhotoService.getPath(goods.getGoodsId()) + "?x-oss-process=image/resize,w_100");
            }

            response = LiveInfoApiResponse.builder()
                    .type(1)
                    .roomId(infoResponse.getRoomId())
                    .name(infoResponse.getName())
                    .photo(infoResponse.getPhoto())
                    .preTime(DateUtil.format(formatter, infoResponse.getPreTime()))
                    .remainingTime(infoResponse.countRemainingTime())
                    .goodsNum(goodsNum)
                    .goodsPhotos(goodsPhotos)
                    .build();
        } else {//创建
            List<SysDictValue> dictValues = sysDictValueService.getList(SysDictValueService.Type.LIVE_TYPE, SysDictValueService.DEFAULT_COMPANY_KEY);
            List<LiveInfoApiResponse.Type> types = ConvertUtils.list(dictValues, dict -> LiveInfoApiResponse.Type.builder()
                    .typeId(Integer.valueOf(dict.getName()))
                    .typeName(dict.getValue())
                    .build());

            response = LiveInfoApiResponse.builder()
                    .type(0)
                    .types(types)
                    .build();
        }

        return ResultModel.success(response);
    }

    @ApiOperation(value = "2创建直播")
    @PostMapping("save")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel save(@RequestAttribute LiveSaveApiRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        boolean hasLive = companyBaseService.isByLabel(optUser.getCompanyId(), CompanyBaseService.LABEL_LIVE);
        AssertUtil.isTrue(hasLive, ResultEnum.PARAM_CHECK, "您当前还没有直播权限，详情咨询客服");

        LiveSaveRequest saveRequest = LiveSaveRequest.builder()
                .cardId(optUser.getCardId())
                .name(request.getName())
                .photo(request.getPhoto())
                .type(request.getType())
                .preFlag(request.getPreFlag())
                .preTime(DateUtil.getDate(request.getPreTime()))
                .goodsIds(request.getGoodsIds())
                .build();
        ResultModel resultModel = liveFeign.save(saveRequest);
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation(value = "2商品选择列表")
    @GetMapping("goods/select")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<LiveGoodsSelectApiResponse> goodsSelect(@RequestAttribute PageRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        ResultModel<LiveGoodsListResponse> goodsListResponseResultModel = liveFeign.goodsList(LiveGoodsListRequest.builder()
                .cardId(optUser.getCardId())
                .build());
        AssertUtil.isTrue(goodsListResponseResultModel);
        List<LiveGoodsListResponse.Goods> selectGoodsList = goodsListResponseResultModel.getData().getGoodsIds();
        List<Integer> selectGoodsIds = OneListUtil.isNotEmpty(selectGoodsList) ? selectGoodsList.stream().map(LiveGoodsListResponse.Goods::getGoodsId).collect(Collectors.toList()) : null;
        boolean isSelect = OneListUtil.isNotEmpty(selectGoodsIds);

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<Integer> goodsids = goodsApiCrmAppMapper.selectLive(optUser.getCompanyId());
        PageResponse2<LiveGoodsSelectApiResponse.Goods> goodsPageResponse2 = ConvertUtils.page2(goodsids, goodsId -> {
            Goods goods = goodsBaseService.get(goodsId);

            return LiveGoodsSelectApiResponse.Goods.builder()
                    .goodsId(goodsId)
                    .name(goods.getGoodsName())
                    .photo(OneStringUtils.photoResize(goodsPhotoService.getPath(goodsId)))
                    .price(goods.getPrice())
                    .selected(isSelect ? BooleanUtils.toInteger(selectGoodsIds.contains(goodsId)) : (goods.getIsPayment() == 1 ? 0 : -1))
                    .build();
        });

        LiveGoodsSelectApiResponse response = LiveGoodsSelectApiResponse.builder()
                .goodsList(goodsPageResponse2)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "2商品添加")
    @GetMapping("goods/add")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel goodsAdd(@RequestAttribute LiveGoodsAddApiRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        ResultModel resultModel = liveFeign.goodsAdd(LiveGoodsAddRequest.builder()
                .cardId(optUser.getCardId())
                .goodsIds(request.getGoodsIds())
                .build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation(value = "2删除预告")
    @PostMapping("remove")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel remove() {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        LiveRemoveRequest saveRequest = LiveRemoveRequest.builder()
                .cardId(optUser.getCardId())
                .build();
        ResultModel resultModel = liveFeign.remove(saveRequest);
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation(value = "3开播")
    @PostMapping("open")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<LiveOpenApiResponse> open() {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        ResultModel<LiveOpenResponse> resultModel = liveFeign.open(LiveOpenRequest.builder().cardId(optUser.getCardId()).build());
        AssertUtil.isTrue(resultModel);

        Company2Dto company = companyBaseService.get2(optUser.getCompanyId());
        final boolean hasZkgx = companyBaseService.hasZkgx(optUser.getCompanyId());

        LiveOpenApiResponse response = LiveOpenApiResponse.builder()
                .roomId(resultModel.getData().getRoomId())
                .companyName(company.getCompanyName())
                .companyLogo(company.getCompanyLogo())
                .companyLevel(company.countCompanyLevelView())
                .hasZkgx(BooleanUtils.toInteger(hasZkgx))
                .pushUrl(resultModel.getData().getPushUrl())
                .groupId(resultModel.getData().getGroupId())
                .viewerNum(resultModel.getData().getViewerNum())
                .viewerPhotos(resultModel.getData().getViewerPhotos())
                .build();

        return ResultModel.success(response);
    }

    @ApiOperation(value = "3退出直播")
    @PostMapping("quit")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel quit() {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        LiveQuitRequest saveRequest = LiveQuitRequest.builder()
                .cardId(optUser.getCardId())
                .build();
        ResultModel resultModel = liveFeign.quit(saveRequest);
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation(value = "3商品上下架")
    @GetMapping("goods/update")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel goodsUpdate(@RequestAttribute LiveGoodsUpdateApiRequest request) {
        ResultModel resultModel = liveFeign.goodsUpdate(LiveGoodsUpdateRequest.builder()
                .roomGoodsId(request.getRoomGoodsId())
                .status(request.getStatus())
                .build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation(value = "4我的直播-列表")
    @PostMapping("my")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<LiveMyResponse> my(@RequestAttribute LiveMyRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        LiveListRequest liveListRequest = LiveListRequest.builder()
                .cardId(optUser.getCardId())
                .videoType(LiveApi.VIDEO_TYPE_LIVE)
                .build();
        liveListRequest.setPageInit(request.getPageNum(), request.getPageSize());
        ResultModel<LiveListVo> liveListVoResultModel = liveFeign.list(liveListRequest);
        AssertUtil.isTrue(liveListVoResultModel);

        PageResponse2<LiveMyResponse.Room> rooms = ConvertUtils.page2(liveListVoResultModel.getData().getLivePage(), live -> {
            return LiveMyResponse.Room.builder()
                    .roomId(live.getRoomId())
                    .status(live.getStatus())
                    .time(live.getTime().getTime())
                    .preTime(Objects.nonNull(live.getPreTime()) ? live.getPreTime().getTime() : null)
                    .title(live.getTitle())
                    .photo(live.getPhoto())
                    .viewNum(live.getViewNum())
                    .replayUrl(live.getReplayUrl())
                    .build();
        });

        LiveMyResponse.Room roomLast = null;
        if (OneListUtil.isNotEmpty(rooms.getList())) {
            if (rooms.getList().get(0).getStatus() != 2) {
                roomLast = rooms.getList().remove(0);
            }
        }

        int status = 0;//直播开关
        RequestContext requestContext = RequestContextHolder.getRequestContext();
        if (requestContext.isCard()) {
            boolean hasLive = companyBaseService.isByLabel(requestContext.getUser().getCompanyId(), CompanyBaseService.LABEL_LIVE);
            if (hasLive) {
                ResultModel<LiveInfoResponse> infoResponseResultModel = liveFeign.info(LiveInfoRequest.builder()
                        .cardId(requestContext.getUser().getCardId())
                        .build());
                AssertUtil.isTrue(infoResponseResultModel);
                LiveInfoResponse infoResponse = infoResponseResultModel.getData();
                status = !infoResponse.isOn() ? 1 : 2;
            }
        }

        LiveMyResponse response = LiveMyResponse.builder()
                .roomLast(roomLast)
                .rooms(rooms)
                .status(status)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "4我的直播-删除")
    @PostMapping("my/remove")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel myRemove(@RequestAttribute LiveMyRemoveRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        ResultModel resultModel = liveFeign.remove(LiveRemoveRequest.builder().cardId(optUser.getCardId()).roomId(request.getRoomId()).build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }
}
